<template>
    <div class="jianzhan-content">
        <Crumb :name="$t('stockOutApplication.application')"/>
        <div class="content">
            <el-button size="small" @click="openAdd" type="primary" >{{$t('stockOutApplication.addStock')}}
            </el-button>
            <Search>
                <el-input
                        v-model="key"
                        class="input"
                        size="small"
                        prefix-icon="el-icon-search"
                        :placeholder="$t('stockOutApplication.search')"></el-input>
                <el-input
                        v-model="customer"
                        class="input"
                        size="small"
                        prefix-icon="el-icon-search"
                        :placeholder="$t('stockOutApplication.customer')"></el-input>
                <el-button type="primary" size="small" @click="search">{{$t('search')}}</el-button>
                <el-button type="text" @click="showEdit = !showEdit" class="btn">{{btnText}}</el-button>

            </Search>
            <div class="table-wrapper">
                <el-table border
                          v-loading="loading"
                          element-loading-text="Loading.."
                          element-loading-spinner="el-icon-loading"
                          element-loading-background="rgba(0, 0, 0, 0.8)"
                          @expand-change="getPartDetail"
                          @filter-change="handleFilterChange"
                          stripe
                          row-key="id"
                          :data="stockList"
                >
                    <el-table-column type="expand">
                        <template slot-scope="props">
                            <el-table :data="props.row.partList" border>
                                <el-table-column
                                        prop="partsNumber"
                                        :label="$t('part.partNo')"
                                        width="180">
                                </el-table-column>
                                <el-table-column
                                        prop="denomination"
                                        :label="$t('part.description')"
                                >
                                </el-table-column>
                                <el-table-column
                                        prop="designation"
                                        :label="$t('part.description')"
                                >
                                </el-table-column>
                                <el-table-column
                                        prop="partsQuantity"
                                        :label="$t('invoice.qty')"
                                >
                                </el-table-column>
                            </el-table>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="applicationNumber"
                            :label="$t('stockOutApplication.applicationNumber')"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="customer"
                            :label="$t('stockOutApplication.customer')"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="receiver"
                            :label="$t('stockOutApplication.receiver')"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="requestBy"
                            :label="$t('stockOutApplication.requestBy')"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="applicationDateStr"
                            :label="$t('stockOutApplication.applicationDateStr')"
                    >
                    </el-table-column>
                    <el-table-column
                            :label="$t('operate')"
                            v-if="showEdit">
                        <template slot-scope="stock">
                            <el-button type="text" size="small"
                                       @click="showDetail(stock.row)">{{$t('edit')}}
                            </el-button>
                            <el-button type="text" size="small" @click="print(stock.row)">{{$t('print')}}</el-button>
                            <el-button type="text" size="small" @click="deleteApply(stock.row.id)">{{$t('delete')}}</el-button>
                        </template>
                    </el-table-column>
                </el-table>

            </div>


                <div class="page">
                    <el-pagination background
                                   :page-size="pageSize"
                                   @current-change="changePage"
                                   layout="prev, pager, next"
                                   :total="total"></el-pagination>
                </div>
            </div>

        <!--dialog-->
        <el-dialog
                :title="$t('stockOutApplication.application')"
                :visible.sync="dialogVisible"
                width="80%"
                >
            <el-form ref="form" :model="stock" label-width="180px" >
                <el-form-item :label="$t('stockOutApplication.supplier')">
                    <span>PT.Indonesia Line</span>
                </el-form-item>
                <el-form-item :label="$t('stockOutApplication.applicationNumber')">
                    <el-input v-model="stock.applicationNumber" :placeholder="$t('stockOutApplication.applicationNumber')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('stockOutApplication.applicationDateStr')">
                    <el-date-picker v-model="stock.applicationDateStr" value-format="yyyy-MM-dd"></el-date-picker>
                </el-form-item>
                <el-form-item :label="$t('stockOutApplication.requestBy')">
                    <el-select v-model="stock.requestBy" filterable :placeholder="$t('stockOutApplication.requestBy')">
                        <el-option
                                v-for="item in requestByList"
                                :key="item.id"
                                :label="item.employeeName"
                                :value="item.employeeName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('stockOutApplication.customer')">
                    <el-select v-model="stock.customer" filterable :placeholder="$t('stockOutApplication.customer')">
                        <el-option
                                v-for="item in customerList"
                                :key="item.id"
                                :label="item.customerName"
                                :value="item.customerName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('stockOut.receiver')" prop="receiver">
                    <el-select v-model="stock.receiver" placeholder="Receiver" filterable
                               :disabled="!isDisabled">
                        <el-option
                                v-for="item in employeeList"
                                :key="item.id"
                                :label="item.contactName"
                                :value="item.contactName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-button style="float: left;margin-bottom: 10px;" type="primary" icon="el-icon-plus" @click="dbVisible = true">Add</el-button>
                <Data-Base @deleteItem="deleteItem" :show-sale="false" :partList="partList" :isDisabled="isDisabled"/>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </span>
        </el-dialog>
        <el-dialog
                title="Print"
                :visible.sync="dialogVisible1"
                width="90%"
                >
            <div class="print-area" ref="print">
                <div class="title">BUKTI PENGELU SPAREPART DARI WAREHOUSE IEL</div>
                <div class="flex">
                    <div class="text f2">Nama Perusahaan :PT.Indonesia Line</div>
                    <div class="text f1">{{time}}</div>
                    <div class="text f1">{{stock.applicationNumber}}</div>
                </div>
                <div class="flex">
                    <div class="text f1">Company 客户公司: {{stock.customer}}</div>
                    <div class="text f1">Date日期: {{stock.applicationDateStr}}</div>
                </div>
                <div class="table-wrapper">
                    <div class="table">
                        <div class="tr">
                            <div class="td f1">No</div>
                            <div class="td f2">仓库代码</div>
                            <div class="td f3">配件编号</div>
                            <div class="td f3">中文描述</div>
                            <div class="td f1">单位</div>
                            <div class="td f1">申报量</div>
                            <div class="td f1">签收数量</div>
                            <div class="td f2">车型</div>
                            <div class="td f2">备注</div>
                        </div>
                        <div class="tr" v-for="(item,idx) in partList" :key="item.id">
                            <div class="td f1">{{idx+1}}</div>
                            <div class="td f2"></div>
                            <div class="td f3">{{item.partsNumber}}</div>
                            <div class="td f3">{{item.denomination}}</div>
                            <div class="td f1">个</div>
                            <div class="td f1">{{item.partsQuantity}}</div>
                            <div class="td f1"></div>
                            <div class="td f2">{{item.hostNumber}}</div>
                            <div class="td f2"></div>
                        </div>

                    </div>
                </div>
                <div class="footer flex">
                    <div class="text f1">汽配仓库</div>
                    <div class="text f1">寄售仓库</div>
                    <div class="text f1">领用部门验收人</div>
                    <div class="text f1">汽修厂领导签字</div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible1 = false">{{$t('cancel')}}</el-button>
            <el-button type="primary" @click="prt">{{$t('print')}}</el-button>
          </span>
        </el-dialog>
        <Part-item @close="dbVisible = false" @add="add" :visible="dbVisible" :belong-module='belongModule'/>
    </div>

    </div>
</template>

<script>
    import Crumb from '../../components/common/crumb'
    import Search from '../../components/common/search'
    import PartItem from '../../components/part/sparePartItem'
    import DataBase from '../../components/part/spDataBase'
    import {mapActions} from 'vuex'
    import moment from 'moment'
    import {
        getStockOutApplicationList,
        addStockOutApplication,
        stockOutApplicationDetail,
        updateStockOutApplication,
        deleteApply
    } from "../../api/service";
    import {getCustomerEmployee, getSpecCustomer} from "../../api/customer";
    import {ERROR_OK} from "../../util/config";
    import mixins from '../../util/mixins'
    import spMixins from '../../util/spMixins'
    import authMixins from '../../util/authMixins'
    import {getEmployeeList} from "../../api";
    export default {
        name: "stock-out-application",
        mixins: [mixins, spMixins, authMixins],
        props: {
            belongModule: {
                type: Number,
            },
        },
        data() {
            return {
                list: [],
                requestByList:[],
                showEdit: false,
                loading: true,
                stock: {
                    id:'',
                    applicationNumber:'',
                    supplier:'PT.Indonesia Line',
                    customer:'',
                    requestBy:'',
                    receiver:'',
                    applicationDateStr:'',
                    belongModule:'',
                    stockOutApplicationDetailList:[]
                },
                key: '',
                time:moment().format('YYYY/MM/DD hh:mm'),
                customerList: [],
                dialogVisible: false,
                dialogVisible1: false,
                editable: true,
                isDisabled: true,
                customer:''
            }
        },
        computed: {
            btnText() {
                return this.showEdit ? 'Complete' : 'Edit'
            },
            stockList() {
                return this.list
            }
        },
        created() {
            this._getStockOutList();
            this._getEmployeeList();
            this.getSpecCustomer();
        },
        methods: {
            async deleteApply(id){
                this.$confirm('','是否删除').then(async ()=>{
                    const {status,msg} = await deleteApply(id);
                    if(status === ERROR_OK) {
                        this.$message.success('删除成功');
                        const idx = this.list.findIndex(item=>item.id===id);
                        this.list.splice(idx,1)
                    } else {
                        this.$message.error(msg)
                    }
                })
            },
            prt(){
                this.$print(this.$refs.print) // 使用
            },
                async getPartDetail(r) {
                    if (r.partList) {
                        return
                    }
                    const {status, data} = await stockOutApplicationDetail(r.id);
                    if (status === ERROR_OK) {
                        r.partList = data.stockOutApplicationDetailVos.map(item => {
                            return {...item,
                                id:item.partsId,
                                number:item.partsQuantity}
                        });
                        const index = this.list.findIndex(item => item.id === r.id);
                        this.list.splice(index, 1, r);
                    }

                },
            async showDetail(row){
                const {status,data} = await stockOutApplicationDetail(row.id);
                if(status === ERROR_OK) {
                    this.stock = row;
                    this.partList = data.stockOutApplicationDetailVos.map(item => {
                        return {...item,
                            id:item.partsId,
                            number:item.partsQuantity}
                    });
                    this.dialogVisible = true;

                }
            },
            async print(row) {
                const {status,data} = await stockOutApplicationDetail(row.id);
                if(status === ERROR_OK) {
                    this.stock = row;
                    this.partList = data.stockOutApplicationDetailVos.map(item => {
                        return {...item,number:item.partsQuantity}
                    });
                }
                this.dialogVisible1 = true

            },
            handleFilterChange(filter) {
                this.pageNum = 1;
                Object.keys(filter).forEach((key) => {
                    this[key] = filter[key][0]
                });
                this._getStockOutList()
            },
            async getSpecCustomer() {
                const {status, data} = await getSpecCustomer();
                if (status === 0) {
                    this.customerList = data;
                }
            },
            async _getEmployeeList() {
                const {status, data} = await getEmployeeList();
                if (status === ERROR_OK) {
                    this.requestByList = data.list
                }
            },
            async submitForm() {
                let {applicationNumber,applicationDateStr,customer,supplier,requestBy,receiver,id} = this.stock;
                let stockOutApplicationDetailList = this.partList.map(item => {
                    return {
                        partsId: item.id || item.partsId,
                        partsQuantity: item.number,
                    }
                });
                stockOutApplicationDetailList = JSON.stringify(stockOutApplicationDetailList);
                if(!id){
                    const {status,msg} = await addStockOutApplication({
                        supplier,
                        requestBy,
                        receiver,
                        applicationNumber,
                        applicationDateStr,
                        customer,
                        stockOutApplicationDetailList,
                        belongModule:this.belongModule
                    });
                    if(status === ERROR_OK) {
                        this.$message.success('Add Success');
                        this.clear();
                        this.dialogVisible = false;
                        this._getStockOutList()
                    } else {
                        this.$message.error(msg)
                    }
                } else {
                    const {status,msg} = await updateStockOutApplication({
                        id,
                        supplier,
                        requestBy,
                        receiver,
                        applicationNumber,
                        applicationDateStr,
                        customer,
                        stockOutApplicationDetailList,
                        belongModule:this.belongModule
                    });
                    if(status === ERROR_OK) {
                        this.$message.success('Update Success');
                        this.clear();
                        this.dialogVisible = false;
                        this._getStockOutList()
                    } else {
                        this.$message.error(msg)
                    }
                }
            },

            changePage(page){
                this.pageNum = page;
                this._getStockOutList();
            },
            async _getStockOutList() {
                const {status, data} = await getStockOutApplicationList(
                    {
                        customer:this.customer,
                        pageNum:this.pageNum,
                        pageSize:100,
                        belongModule:this.belongModule,
                        applicationNumber:this.key
                    }
                );
                if (status === ERROR_OK) {
                    this.list = data.list;
                    this.total = data.total;
                    this.loading = false
                }  else {
                    this.loading = false
                }
            },
            async search(){
                this.pageNum = 1;
                this._getStockOutList()
            },

            clear() {
                this.partList = [];
                this.stock = {
                    id:'',
                    applicationNumber:'',
                    supplier:'PT.Indonesia Line',
                    customer:'',
                    requestBy:'',
                    receiver:'',
                    applicationDateStr:'',
                    belongModule:'',
                    stockOutApplicationDetailList:[]
                }
            },
            async getEmployeeList(customerId) {
                const {status, data} = await getCustomerEmployee(customerId);
                if (status === ERROR_OK) {
                    this.employeeList = data;
                } else {
                    this.employeeList = []
                }
                this.$forceUpdate()
            },
            openAdd() {
                this.editable = true;
                this.dialogVisible = true;
                this.clear()
            },
            ...mapActions(['modPartNum'])
        },
        watch:{
            'stock.customer': {
                handler: function (customer) {
                    if (!customer) {
                        this.$set(this.stock,'receiver','');
                    } else {
                        const target = this.customerList.filter(item => item.customerName === customer)[0];
                        if (target) {
                            this.getEmployeeList(target.id);
                        }
                    }
                },
                deep: true
            },
        },
        components: {
            Crumb, Search, PartItem, DataBase
        }
    }
</script>

<style scoped lang="scss">
    @import "../../css/mixins";

    .content {
        @include content
    }

    .btn {
        float: right;
        margin-right: 20px;
        transition: all 1s ease;
        opacity: 0.5;
        &:hover {
            opacity: 1;
        }
    }
    .print-area{
        width: 297mm;
        height: 210mm;
        padding:20px;
        .title{
            font-size: 16px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 5px;
        }
        .table-wrapper{
            margin-top: 10px;
            margin-bottom: 20px;
            .table{
                border: 2px solid #000000;
                text-align: center;
                .tr{
                    display: flex;
                    border:1px solid #ddd;
                    .td{
                        height: 30px;
                        line-height: 30px;
                        border-left: 1px solid #ddd;
                    }
                }
            }
        }
        .flex{
            display: flex;
        }
        .f1{
            flex: 1;
        }
        .f2{
            flex: 2;
        }
        .f3{
            flex: 3;
        }
    }
    @page {
        size: A4;
        margin: 0;
    }
    @media print {
        .print-area{
            width: 297mm;
            height: 210mm;
            padding:14px;
            .title{
                font-size: 16px;
                font-weight: bold;
                text-align: center;
                margin-bottom: 5px;
            }
            .table-wrapper{
                margin-top: 10px;
                margin-bottom: 20px;
                .table{
                    border: 2px solid #000000;
                    .tr{
                        display: flex;
                        border:1px solid #ddd;
                        .td{
                            height: 30px;
                            line-height: 30px;
                            border-left: 1px solid #ddd;
                        }
                    }
                }
            }
            .flex{
                display: flex;
            }
            .f1{
                flex: 1;
            }
            .f2{
                flex: 2;
            }
            .f3{
                flex: 3;
            }
        }

    }
</style>